package br.com.portalecbahia;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import com.google.analytics.tracking.android.EasyTracker;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import br.com.portalecbahia.connectionservices.SynchronizeMatch;
import br.com.portalecbahia.customize.MatchListAdapter;
import br.com.portalecbahia.customize.PullToRefreshListView;
import br.com.portalecbahia.customize.PullToRefreshListView.OnRefreshListener;
import br.com.portalecbahia.dao.MatchDAO;
import br.com.portalecbahia.listner.MatchListeners;
import br.com.portalecbahia.model.Match;
import br.com.portalecbahia.model.Stadium;
import br.com.portalecbahia.model.TypeMatch;
import br.com.portalecbahia.util.PortalECBahiaUtil;

public class MatchActivity  extends ListActivity implements MatchListeners{
	
	private Context context;
	private List<Match> lMatch;
	private ListAdapter adapterListMatch;
	private SynchronizeMatch taskMatch;
	private TypeMatch currentType ;
	private Button homeBTN;
	private Button allBTN;
	private Button liveBTN;
	private ImageView updateIMG;

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.match);

        EasyTracker.getInstance().setContext(this);

        context = this;
        
        homeBTN = (Button) findViewById(R.id.homeBTN);
        allBTN = (Button) findViewById(R.id.allBTN);
        liveBTN = (Button) findViewById(R.id.liveBTN);
        updateIMG = (ImageView) findViewById(R.id.updateIMG);

        
        ((PullToRefreshListView) getListView()).setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
            	if(PortalECBahiaUtil.haveNetworkConnection(context)){
            		taskMatch = new SynchronizeMatch(context);
            		taskMatch.execute();
            	}else{
        			Toast.makeText(context, getString(R.string.internetOff), Toast.LENGTH_LONG).show();
        			  ((PullToRefreshListView) getListView()).onRefreshComplete();
            	}
            }
        });
        currentType = new TypeMatch();
        currentType.setId(2l);
       
        updateList(new View(this));

    }
    
    @Override
    public void onStart() {
      super.onStart();
      EasyTracker.getInstance().activityStart(this); // Add this method.
    }

    @Override
    public void onStop() {
      super.onStop();
      EasyTracker.getInstance().activityStop(this); // Add this method.
    }
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		listMatch();
	}
	

	@Override
	public void onSynchronizeMatchComplete(Boolean response) {
		if(response){
			listMatch();
		}else{
			Toast.makeText(context, getString(R.string.serverProblem), Toast.LENGTH_LONG).show();
		}
	    updateIMG.clearAnimation();
	    ((PullToRefreshListView) getListView()).onRefreshComplete();
		
	}
	
	public void updateList(View view){
		if(PortalECBahiaUtil.haveNetworkConnection(context)){
			taskMatch = new SynchronizeMatch(context);
			taskMatch.execute();
			animateUpdate();
    	}else{
			Toast.makeText(context, getString(R.string.internetOff), Toast.LENGTH_LONG).show();
			  ((PullToRefreshListView) getListView()).onRefreshComplete();
    	}

	}

	private void animateUpdate() {
		int   currentRotation = 0;
		RotateAnimation anim = new RotateAnimation(currentRotation, (360*4),
		Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,0.5f);
		currentRotation = (currentRotation + 45) % 360;
		anim.setInterpolator(new LinearInterpolator());
		anim.setDuration(4000);
		anim.setRepeatMode(Animation.INFINITE);
		anim.setRepeatCount(Animation.INFINITE);
		anim.setFillEnabled(true);
		anim.setFillAfter(true);
		updateIMG.startAnimation(anim);
		
	}
	private void listMatch() {
	   	lMatch = new ArrayList<Match>();
    	lMatch.clear();
    	
    	
    	//type Video
    	if(currentType.getId() == 1){
        	lMatch = new MatchDAO(this).findHome();   
        	int sizeList = lMatch.size();
        	if(lMatch.size()<10){    		
        		for (int i = 0; i < PortalECBahiaUtil.minimumListSize-sizeList; i++) {
        			lMatch.add(new Match());
    			}
        	}
        	homeBTN.setBackgroundResource(R.drawable.left_bluebtn);
        	homeBTN.setTextColor(getResources().getColor(R.color.white));
        	
        	allBTN.setBackgroundResource(R.drawable.center_bluebtn_selected);
        	allBTN.setTextColor(getResources().getColor(R.color.gray));
        	
        	liveBTN.setBackgroundResource(R.drawable.right_bluebtn_selected);
        	liveBTN.setTextColor(getResources().getColor(R.color.gray));
        	
        	positionList();
		}else if(currentType.getId() == 2){
			lMatch = new MatchDAO(this).findAll();
			int sizeList = lMatch.size();
	    	if(lMatch.size()<10){    		
	    		for (int i = 0; i < PortalECBahiaUtil.minimumListSize-sizeList; i++) {
	    			lMatch.add(new Match());
				}
	    	}
	      
	    	homeBTN.setBackgroundResource(R.drawable.left_bluebtn_selected);
        	homeBTN.setTextColor(getResources().getColor(R.color.gray));
        	
        	allBTN.setBackgroundResource(R.drawable.center_bluebtn);
        	allBTN.setTextColor(getResources().getColor(R.color.white));
        	
        	liveBTN.setBackgroundResource(R.drawable.right_bluebtn_selected);
        	liveBTN.setTextColor(getResources().getColor(R.color.gray));
        	positionList();
        	        	
		}else if(currentType.getId() == 3){
			lMatch = new MatchDAO(this).findAway();
			int sizeList = lMatch.size();
	    	if(lMatch.size()<10){    		
	    		for (int i = 0; i < PortalECBahiaUtil.minimumListSize-sizeList; i++) {
	    			lMatch.add(new Match());
				}
	    	}
	      
	    	homeBTN.setBackgroundResource(R.drawable.left_bluebtn_selected);
        	homeBTN.setTextColor(getResources().getColor(R.color.gray));
        	
        	allBTN.setBackgroundResource(R.drawable.center_bluebtn_selected);
        	allBTN.setTextColor(getResources().getColor(R.color.gray));
        	
        	liveBTN.setBackgroundResource(R.drawable.right_bluebtn);
        	liveBTN.setTextColor(getResources().getColor(R.color.white));
        	positionList();       	
		}
    	adapterListMatch = (ListAdapter) new MatchListAdapter(this, lMatch);

	    setListAdapter(adapterListMatch);
	  
	}
	
	public void listHome(View view){
		currentType.setId(1l);
		listMatch();
	}
	public void listAll(View view){
		currentType.setId(2l);
		listMatch();
	}
	
	
	
	public void listLive(View view){
		currentType.setId(3l);
		listMatch();
	}

	public void positionList(){
		getListView().post(new Runnable(){
       	  public void run() {
       		  getListView().setSelection(getPositionNextMatch(lMatch));
       	  }

			private int getPositionNextMatch(List<Match> lMatch) {
				int i = 0;
				for (Match match : lMatch) {
					i++;
					if(match!=null && match.getFinished()!=null && match.getFinished()==false){
						return i;
					}
						
				}
				if(lMatch!=null) {
					return lMatch.size();
				} else {
					return 0;
				}
			}});
  	 
	}

	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) { 
		super.onListItemClick(l, v, position, id);
		
		Match matchSelect = (Match) (adapterListMatch.getItem(position-1));
		Intent intent = null;
		
		SimpleDateFormat formatUTC = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        formatUTC.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date now=null;
		try {
			now = (Date) (new SimpleDateFormat("yyyy-MM-dd HH:mm")).parse(formatUTC.format(new Date()));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	
		if(matchSelect!=null && matchSelect.getId()!=null){
			
			if(	!now.before(matchSelect.getDateUTC()) && matchSelect.getLive()){
				
				intent = new Intent(this, ActionActivity.class);
				intent.putExtra("match", matchSelect);
			}else{
				Stadium stadium = new Stadium();
				stadium.setId(matchSelect.getStadiumId());
				stadium.setName(matchSelect.getStadimName());

				intent = new Intent(this, StadiumActivity.class);
				intent.putExtra("stadium", stadium);
			}
			startActivity(intent);
		}
		return;
	}

	
    
}
